#!/bin/bash

# OrbbecSDK Python绑定构建脚本
# 使用方法: ./build.sh [选项]

set -e  # 遇到错误立即退出

# 默认配置
BUILD_TYPE="Release"
BUILD_PYTHON="ON"
INSTALL_PREFIX="/usr/local"
CLEAN_BUILD=false
VERBOSE=false

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印帮助信息
print_help() {
    echo "OrbbecSDK Python绑定构建脚本"
    echo ""
    echo "使用方法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  -h, --help              显示此帮助信息"
    echo "  -t, --type TYPE         构建类型 (Debug|Release) [默认: Release]"
    echo "  -p, --python ON|OFF     是否构建Python绑定 [默认: ON]"
    echo "  -i, --install PREFIX    安装前缀 [默认: /usr/local]"
    echo "  -c, --clean             清理构建目录"
    echo "  -v, --verbose           详细输出"
    echo ""
    echo "示例:"
    echo "  $0                      # 默认构建"
    echo "  $0 -t Debug -p OFF      # 构建Debug版本，不包含Python绑定"
    echo "  $0 -c                   # 清理构建目录"
    echo "  $0 -i /opt/orbbec       # 安装到/opt/orbbec"
}

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            print_help
            exit 0
            ;;
        -t|--type)
            BUILD_TYPE="$2"
            shift 2
            ;;
        -p|--python)
            BUILD_PYTHON="$2"
            shift 2
            ;;
        -i|--install)
            INSTALL_PREFIX="$2"
            shift 2
            ;;
        -c|--clean)
            CLEAN_BUILD=true
            shift
            ;;
        -v|--verbose)
            VERBOSE=true
            shift
            ;;
        *)
            echo -e "${RED}错误: 未知选项 $1${NC}"
            print_help
            exit 1
            ;;
    esac
done

# 验证构建类型
if [[ "$BUILD_TYPE" != "Debug" && "$BUILD_TYPE" != "Release" ]]; then
    echo -e "${RED}错误: 无效的构建类型 '$BUILD_TYPE'。请使用 Debug 或 Release${NC}"
    exit 1
fi

# 验证Python选项
if [[ "$BUILD_PYTHON" != "ON" && "$BUILD_PYTHON" != "OFF" ]]; then
    echo -e "${RED}错误: 无效的Python选项 '$BUILD_PYTHON'。请使用 ON 或 OFF${NC}"
    exit 1
fi

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
BUILD_DIR="$PROJECT_ROOT/cmake-build-$BUILD_TYPE"

echo -e "${BLUE}=== OrbbecSDK Python绑定构建脚本 ===${NC}"
echo -e "${BLUE}项目根目录: $PROJECT_ROOT${NC}"
echo -e "${BLUE}构建目录: $BUILD_DIR${NC}"
echo -e "${BLUE}构建类型: $BUILD_TYPE${NC}"
echo -e "${BLUE}Python绑定: $BUILD_PYTHON${NC}"
echo -e "${BLUE}安装前缀: $INSTALL_PREFIX${NC}"
echo ""

# 检查依赖
echo -e "${YELLOW}检查依赖...${NC}"

# 检查CMake
if ! command -v cmake &> /dev/null; then
    echo -e "${RED}错误: 未找到CMake。请安装CMake 3.12或更高版本${NC}"
    exit 1
fi

CMAKE_VERSION=$(cmake --version | head -n1 | cut -d' ' -f3)
echo -e "${GREEN}✓ CMake版本: $CMAKE_VERSION${NC}"

# 检查OpenCV
if ! pkg-config --exists opencv4; then
    echo -e "${YELLOW}警告: 未找到OpenCV4，尝试查找OpenCV3...${NC}"
    if ! pkg-config --exists opencv; then
        echo -e "${RED}错误: 未找到OpenCV。请安装OpenCV开发包${NC}"
        exit 1
    fi
fi
echo -e "${GREEN}✓ OpenCV已安装${NC}"

# 检查Python（如果需要构建Python绑定）
if [[ "$BUILD_PYTHON" == "ON" ]]; then
    if ! command -v python3 &> /dev/null; then
        echo -e "${RED}错误: 未找到Python3。请安装Python3开发包${NC}"
        exit 1
    fi
    
    PYTHON_VERSION=$(python3 --version | cut -d' ' -f2)
    echo -e "${GREEN}✓ Python版本: $PYTHON_VERSION${NC}"
    
    # 检查pip
    if ! command -v pip3 &> /dev/null; then
        echo -e "${YELLOW}警告: 未找到pip3，可能无法安装Python依赖${NC}"
    else
        echo -e "${GREEN}✓ pip3已安装${NC}"
    fi
fi

# 清理构建目录
if [[ "$CLEAN_BUILD" == true ]]; then
    echo -e "${YELLOW}清理构建目录...${NC}"
    if [[ -d "$BUILD_DIR" ]]; then
        rm -rf "$BUILD_DIR"
        echo -e "${GREEN}✓ 构建目录已清理${NC}"
    else
        echo -e "${YELLOW}构建目录不存在，无需清理${NC}"
    fi
    exit 0
fi

# 创建构建目录
echo -e "${YELLOW}创建构建目录...${NC}"
mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"

# 配置CMake
echo -e "${YELLOW}配置CMake...${NC}"
CMAKE_ARGS=(
    "-DCMAKE_BUILD_TYPE=$BUILD_TYPE"
    "-DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX"
    "-DBUILD_PYTHON_BINDINGS=$BUILD_PYTHON"
)

if [[ "$VERBOSE" == true ]]; then
    CMAKE_ARGS+=("-DCMAKE_VERBOSE_MAKEFILE=ON")
fi

cmake "${CMAKE_ARGS[@]}" "$PROJECT_ROOT"

if [[ $? -ne 0 ]]; then
    echo -e "${RED}错误: CMake配置失败${NC}"
    exit 1
fi

echo -e "${GREEN}✓ CMake配置成功${NC}"

# 构建项目
echo -e "${YELLOW}构建项目...${NC}"
MAKE_ARGS=("-j$(nproc)")

if [[ "$VERBOSE" == true ]]; then
    MAKE_ARGS+=("VERBOSE=1")
fi

make "${MAKE_ARGS[@]}"

if [[ $? -ne 0 ]]; then
    echo -e "${RED}错误: 构建失败${NC}"
    exit 1
fi

echo -e "${GREEN}✓ 构建成功${NC}"

# 运行测试（如果存在）
if [[ -f "$BUILD_DIR/bin/test_function" ]]; then
    echo -e "${YELLOW}运行测试...${NC}"
    cd "$BUILD_DIR/bin"
    ./test_function
    if [[ $? -eq 0 ]]; then
        echo -e "${GREEN}✓ 测试通过${NC}"
    else
        echo -e "${YELLOW}警告: 测试失败${NC}"
    fi
fi



# 显示构建结果
echo ""
echo -e "${GREEN}=== 构建完成 ===${NC}"
echo -e "${GREEN}构建目录: $BUILD_DIR${NC}"
echo -e "${GREEN}库文件: $BUILD_DIR/lib/libSCV_ORBBEC_W.so${NC}"

if [[ "$BUILD_PYTHON" == "ON" ]]; then
    echo -e "${GREEN}Python模块: $BUILD_DIR/pyblink*.so${NC}"
    echo ""
    echo -e "${BLUE}Python使用示例:${NC}"
    echo -e "${BLUE}  cd $BUILD_DIR/bin${NC}"
    echo -e "${BLUE}  python3 python_example.py${NC}"
fi

echo ""
echo -e "${BLUE}安装命令:${NC}"
echo -e "${BLUE}  cd $BUILD_DIR${NC}"
echo -e "${BLUE}  sudo make install${NC}"